import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtTabs, AtTabsPane, AtButton, AtTag, AtIcon, AtFloatLayout} from 'taro-ui'
import {View, Navigator, Block, Text, Image} from '@tarojs/components'
import {user} from '../../utils/user.service'
import {OrderDetail as OrderDetailType, TicketItem, SiteOrderLog} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {GET_ORDER_DETAIL, GET_ORDER_TICKET, GET_QRCODE, SITE_ORDER_LOG} from '../../constants/api'
import {convert2CamelCase, GetRequest, vcmonitor} from '../../utils/tools'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './order-detail.scss'

const goodsType = {
  limit: 'limited',
  ticket: 'scenic',
  hotel: 'hotel',
  toursLine: 'tourist-line',
  product: 'product'
}

export default class OrderDetail extends Component {
  tabs = [{title: '订单详情'}, {title: '验证码信息'}, {title: '订单日志'}]
  state: {
    tabsIndex: number
    orderInfo: OrderDetailType | false
    orderTicket: TicketItem[]
    siteOrderLog: SiteOrderLog[]
    goodDetailUrl: string
    openGroup: boolean
    assembling_place_list: any
    openAssembling: boolean
  } = {
    tabsIndex: 0,
    orderInfo: false,
    orderTicket: [],
    siteOrderLog: [],
    goodDetailUrl: '',
    openGroup: false,
    assembling_place_list: [],
    openAssembling: false
  }

  tabsChange(index) {
    this.setState({tabsIndex: index})
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const {orderId} = Taro.getCurrentInstance().router.params
    if (!orderId) {
      Taro.showToast({title: '参数错误', icon: 'none'})
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack({
          delta: 1
        })
      }, 1500);
    }
    Taro.showLoading({title: '加载中...'})
    const orderInfo = await http.get<OrderDetailType>(GET_ORDER_DETAIL, {orderId})
    if (orderInfo.assembling_place) {
      this.setState({
        assembling_place_list: JSON.parse(orderInfo.assembling_place)
      })
    }
    const orderTicket = await http.get<TicketItem[]>(GET_ORDER_TICKET, {orderId})
    let siteOrderLog: SiteOrderLog[] = []
    let url = '';
    if (orderInfo) {
      url = `/common/${goodsType[convert2CamelCase(orderInfo.goodsType)]}/detail?itemId=${orderInfo.guuid || ''}`;
      const res = await http.post<SiteOrderLog[]>(SITE_ORDER_LOG, {orderId: orderInfo.id})
      if (res) {
        siteOrderLog = res
      }
    }

    this.setState({orderInfo, orderTicket, siteOrderLog, goodDetailUrl: url})
    Taro.hideLoading()
  }

  copy() {
    if (this.state.orderInfo) {
      try {
        Taro.setClipboardData({
          data: this.state.orderInfo.order_num
        })
        if (process.env.TARO_ENV === 'h5') {
          Taro.showToast({title: '复制成功'})
        }
      } catch (e) {
        Taro.showToast({title: '复制失败'})
      }
    } else {
      Taro.showToast({title: '复制失败'})
    }

  }

  async getWxQrcode() {
    const orderId = this.state.orderInfo && this.state.orderInfo.id
    Taro.request({
      url: http.url(GET_QRCODE),
      data: {orderId},
      responseType: 'arraybuffer',
      method: 'POST',
      header: await http.getHeader({'Content-Type': 'application/x-www-form-urlencoded'})
    }).then(res => {
      let base64 = ''
      if (res.statusCode === 200) {
        base64 = Taro.arrayBufferToBase64(res.data)
      }
      Taro.previewImage({
        current: '',
        urls: ['data:image/png;base64,' + base64]
      })
    })
  }

  handleClickGroup() {
    const openGroup = this.state.openGroup
    this.setState({
      openGroup: !openGroup
    })
  }

  handleAssembling() {
    const openAssembling = this.state.openAssembling
    this.setState({
      openAssembling: !openAssembling
    })
  }

  onCopy(str) {
    try {
      Taro.setClipboardData({
        data: str
      })
      if (process.env.TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  async showCode(item) {
    if (item.code_type == 2) {
      Taro.previewImage({
        current: item.ticket, // 当前显示图片的http链接
        urls: [item.ticket] // 需要预览的图片http链接列表
      })
    } else {
      this.onCopy(item.ticket)
    }
  }

  showImg(current) {
    Taro.previewImage({
      current,
      urls: [current]
    })
  }

  render() {
    const {tabsIndex, orderInfo, orderTicket, siteOrderLog, goodDetailUrl, openGroup, assembling_place_list, openAssembling} = this.state
    if (!orderInfo) {
      return
    }
    return (
      <View className='site-out-detail-root'>
        <GzhAuth />
        <AtTabs tabList={this.tabs} current={tabsIndex} onClick={this.tabsChange.bind(this)}>
          <AtTabsPane current={tabsIndex} index={0}>
            <View className='head'>
              <View className='title'>订单号: <AtTag circle type='primary' size='small'>点击可复制</AtTag></View>
              <View className='no' onClick={this.copy.bind(this)}>{orderInfo && orderInfo.order_num}</View>
            </View>
            <View className='content'>
              <View className='item'><View className='title'>订单状态:</View><View
                className='text'
              >{orderInfo && orderInfo.status}</View></View>
              <View className='item'><View className='title'>商品名称:</View><View
                className='text'
              >{orderInfo && orderInfo.name}</View></View>
              {orderInfo && orderInfo.meals && orderInfo.meals.length > 0 &&
              <View className='group' onClick={this.handleClickGroup.bind(this)}><View
                className='group-title'
              ><Text>套餐包含</Text> <AtIcon value={openGroup ? 'chevron-down' : 'chevron-right'}
                size='15' color='#ccc'
              ></AtIcon></View></View>}
              {assembling_place_list && assembling_place_list.length > 0 &&
              <View className='group' onClick={this.handleAssembling.bind(this)}><View
                className='group-title'
              ><Text>集结地点</Text> <AtIcon
                value={openAssembling ? 'chevron-down' : 'chevron-right'} size='15'
                color='#ccc'
              ></AtIcon></View></View>}
              {orderInfo.buy_date && orderInfo.goodsType != 'product' &&
              <View className='item'><View className='title'>可用日期:</View><View
                className='text'
              >{orderInfo && orderInfo.buy_date}</View></View>}
              {orderInfo && orderInfo.unit_fee && orderInfo.pay_type != 4 &&
              <View className='item'><View className='title'>商品单价:</View><View
                className='text'
              >¥{orderInfo && orderInfo.unit_fee}</View></View>}
              <View className='item'><View className='title'>购买数量:</View><View
                className='text'
              >{orderInfo && orderInfo.buy_amount}</View></View>
              <View className='item'><View className='title'>购买人:</View><View
                className='text'
              >{orderInfo && orderInfo.nick_name}</View></View>
              <View className='item'><View className='title'>接收人姓名:</View><View
                className='text'
              >{orderInfo && orderInfo.linkman}</View></View>
              <View className='item'><View className='title'>接收人手机:</View><View
                className='text'
              >{orderInfo && orderInfo.phone}</View></View>
              {orderInfo && orderInfo.address && <View className='item'><View className='title'>接收人地址:</View><View
                className='text'
              >{orderInfo && orderInfo.address}</View></View>}
              {orderInfo && orderInfo.defined_img && <View className='group-title'
                onClick={this.showImg.bind(this, orderInfo.defined_img)}
              ><Text>图片:</Text><AtIcon
                value='chevron-right' size='15' color='#ccc'
              ></AtIcon></View>}
              {orderInfo && orderInfo.remark && <View className='item'><View className='title'>备注:</View><View
                className='text'
              >{orderInfo && orderInfo.remark}</View></View>}
              {orderInfo.pay_type != 4 && <View className='item'><View className='title'>订单金额:</View><View
                className='text'
              >¥{orderInfo && orderInfo.total_fee}</View></View>}
              {orderInfo && orderInfo.offpay_date && <View className='item'><View className='title'>支付时间:</View><View
                className='text'
              >{orderInfo && orderInfo.offpay_date}</View></View>}
              {orderInfo && orderInfo.pay_notice_mark &&
              <View className='item'><View className='title'>产品备注:</View><View
                className='text'
              >{orderInfo && orderInfo.pay_notice_mark}</View></View>}
              {orderInfo && orderInfo.site_remark_for_customer &&
              <View className='item'><View className='title'>其他信息:</View><View
                className='text'
              >{orderInfo && orderInfo.site_remark_for_customer}</View></View>}
              {orderInfo && orderInfo.pay_source_name &&
              <View className='item'><View className='title'>订单来源:</View><View
                className='text'
              >{orderInfo && orderInfo.pay_source_name}</View></View>}
            </View>
            <View className='btn'>
              <View className='item'>
                {/*{(orderInfo && orderInfo.order_status==1&&orderInfo && orderInfo.is_allow_refund==1&&(orderInfo && orderInfo.group_id === 0||orderInfo && orderInfo.group_id==null)) && <AtButton type="secondary">申请退款</AtButton>}*/}
                {(orderInfo && orderInfo.order_status == 90 && orderInfo && orderInfo.is_allow_refund == 1) &&
                <AtButton type='secondary' disabled>退款处理中</AtButton>}
              </View>
            </View>
          </AtTabsPane>
          <AtTabsPane current={tabsIndex} index={1}>
            {orderTicket && orderTicket.length === 0 && <View className='sms-box'>
              <View className='sms'>
                请以收到的短信通知为准
              </View>
            </View>}
            {!orderTicket && <View className='sms-box'>
              <View className='sms'>
                请以收到的短信通知为准
              </View>
            </View>}
            {orderTicket && orderTicket.length > 0 && orderTicket.map(item => <Block key={item.id}>
              {item.code_type == 0 && <View className='ticket-num'>
                <View>验证码</View><View className='num'
                  onClick={this.showCode.bind(this, item)}
                >{item.ticket}</View></View>}
              {item.code_type == 1 && <View className='ticket-num'>
                <View>文字码</View><View className='text-type'
                  onClick={this.showCode.bind(this, item)}
                >{item.ticket}</View></View>}
              {item.code_type == 2 && <View className='ticket-num'>
                <View>图片码</View><View className='img-type' onClick={this.showCode.bind(this, item)}><Image
                  src={item.ticket} mode='widthFix'
                ></Image></View></View>}
              {item.code_type == 3 && <View className='ticket-num'>
                <View>链接码</View><View className='link-type'
                  onClick={this.showCode.bind(this, item)}
                >{item.ticket}</View></View>}
              <View className='ticket-info'>
                {item.valid_date_end && item.valid_date_end && <View className='info-item'>
                  <View>有效期</View>
                  <View>{item.valid_date_end} 至 {item.valid_date_end}</View>
                </View>}
                <View className='info-item'>
                  <View>状态</View>
                  <View>{item.isUse}</View>
                </View>
                {item.use_date && <View className='info-item'>
                  <View>使用日期</View>
                  <View>{item.use_date}</View>
                </View>}
              </View>
            </Block>)}
          </AtTabsPane>
          <AtTabsPane current={tabsIndex} index={2}>
            {siteOrderLog.length > 0 && siteOrderLog.map(item => <View className='message' key={item.id}>
              <Text decode>{item.add_date} &nbsp; &nbsp;{item.message}</Text>
            </View>)}
          </AtTabsPane>
        </AtTabs>
        {orderInfo && orderInfo.meals && orderInfo.meals.length > 0 &&
        <AtFloatLayout isOpened={openGroup} title='套餐包含' onClose={this.handleClickGroup.bind(this)} scrollY>
          {orderInfo.meals.map((val, i) =>
            <View className='group-item' key={i}>
              <View className='group-name'>
                <View className='group-product'><Text>{val.product_name}</Text><Text
                  className='group-num'
                >x{val.buy_amount}</Text></View>
                <View className='group-company'>{val.company}</View>
              </View>

            </View>
          )}
        </AtFloatLayout>}
        {assembling_place_list && assembling_place_list.length > 0 &&
        <AtFloatLayout isOpened={openAssembling} title='集合地点' onClose={this.handleAssembling.bind(this)} scrollY>
          {assembling_place_list.map((val, i) =>
            <View className='group-item' key={i}>
              <View className='group-name'>
                <View className='group-product'><Text>{val.assembling_place}</Text></View>
              </View>
            </View>
          )}
        </AtFloatLayout>}
        <Navigator className='back-index' url='/pages/index/index' openType='switchTab'><AtButton
          type='secondary'
        >回到首页</AtButton></Navigator>
        <Navigator className='back-index' url={goodDetailUrl}><AtButton type='secondary'>查看商品</AtButton></Navigator>
      </View>
    )
  }
}
